import "./style.scss";

interface History {
  id: number;
  title: string;
  amount: number;
}
// 写一个闭包
function getGenerateID() {
  let id = 0;
  return () => ++id;
}

// 数据区域
// 生成id
const generateID = getGenerateID();
// 存储
// let historyData: History[] =
//   localStorage.getItem("historiesData") === null
//     ? []
//     : (JSON.parse(localStorage.getItem("historiesData")!) as History[]);
const storedData = localStorage.getItem("historiesData");
let historyData: History[] = [];

if (storedData) { // type guard守卫 narrowing down to string
  historyData = JSON.parse(storedData) as History[];
  console.log(historyData);
  
}


// 概览
const balanceEl = document.getElementById("balance")!;
const moneyPlusEl = document.getElementById("money-plus")!;
const moneyMinusEl = document.getElementById("money-minus")!;
// 历史记录
const listEl = document.getElementById("list")!;

// form相关的元素
const titleEl = document.getElementById("title")! as HTMLInputElement;
const amountEl = document.getElementById("amount")! as HTMLInputElement;
const formEl = document.getElementById("form")!;

// 添加数据
function addDataToHistory() {
  if (titleEl.value.trim() === "" || amountEl.value.trim() === "") {
    alert("请输入描述和金额");
    return;
  }
  const history = {
    id: generateID(),
    title: titleEl.value,
    amount: parseInt(amountEl.value),
  };
  historyData.push(history);
  // 渲染这条数据
  addHistoryDOM(history);
  // 更新概览
  updateValues();
  // 更新localStorage
  updateLocalStorage();

  // 清空输入框
  clearFormInputValue();
}

// 清空输入框
function clearFormInputValue() {
  titleEl.value = "";
  amountEl.value = "";
}

// 删除一条记录
function removeHistory(id: number) {
  historyData = historyData.filter((item) => item.id !== id);

  // 清空重新，渲染
  // 列表渲染
  listEl.innerHTML = "";
  // 初始化列表和概览
  init()
  // 更新localStorage
  updateLocalStorage();
}

// 添加history到dom
function addHistoryDOM(history: History) {
  const liEl = document.createElement("li");
  const sign = history.amount < 0 ? "-" : "+";

  liEl.classList.add(history.amount < 0 ? "minus" : "plus");
  liEl.innerHTML = `
        <span>${history.title}</span>
        <span>${sign}${Math.abs(history.amount)}</span>
        <button class="delete-btn" onclick="removeHistory(${
          history.id
        })">X</button>
    `;
  listEl.appendChild(liEl);
}

// 计算更新账户余额，收入，支出
function updateValues() {
  const balance = historyData
    .reduce((acc, item) => (acc += item.amount), 0)
    .toFixed(2);

  const moneyMinus = (
    historyData
      .filter((item) => item.amount < 0)
      .reduce((acc, item) => (acc += item.amount), 0) * -1
  ).toFixed(2);

  const moneyPlus = historyData
    .filter((item) => item.amount > 0)
    .reduce((acc, item) => (acc += item.amount), 0)
    .toFixed(2);

  balanceEl.textContent = balance;
  moneyMinusEl.textContent = moneyMinus;
  moneyPlusEl.textContent = moneyPlus;
}

// 更新localStorage
function updateLocalStorage() {
  localStorage.setItem("historiesData", JSON.stringify(historyData));
}

// 初始化列表和概览
function init(){
  console.log("初始化页面数据");
  historyData.forEach(addHistoryDOM);
  // 概览渲染
  updateValues();
}

formEl.addEventListener("submit", (e) => {
  e.preventDefault();
  // 添加数据到historyData
  addDataToHistory();
});

// 解决添加li的时候button的事件removeHistory undefined
(window as any).removeHistory = removeHistory;
// 因为使用了localStorage，需要在页面加载的时候初始化数据
window.onload = init